package com.cxhome.cxinfox.cxrole;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cxhome.cxinfox.cxmenu.MenuService;
import com.jfinal.plugin.activerecord.Page;
import com.traffic.managent.annotation.ControllerBind;
import com.traffic.managent.base.CxBaseController;
import com.traffic.managent.model.system.Module;
import com.traffic.managent.model.system.Operator;
import com.traffic.managent.model.system.Role;
import com.traffic.managent.util.StringUtils;

/**
 * 角色
 */
@ControllerBind(controllerKey = "/system/cxrole")
public class RoleController extends CxBaseController {

	private static final String path = "/pages/system/cxrole/cxrole_";

	public void index() {
		list();
	}

	public void list() {
		Role model = getModelByAttr(Role.class);

		StringBuilder orderSql = new StringBuilder("");
		// 排序
		String orderBy = getBaseForm().getOrderBy();
		if (StringUtils.isEmpty(orderBy)) {
			orderSql.append(" order by ids desc");
		} else {
			orderSql.append(" order by ").append(orderBy);
		}
		Page<Role> page = RoleService.service.paginate(model, getPaginator(), orderSql);

		setAttr("page", page);
		setAttr("attr", model);
		render(path + "list.html");
	}

	/**
	 * 跳转新增页面
	 */
	public void add() {
		setAttr("selectRole", RoleService.service.selectRole(""));
		render(path + "add.html");
	}

	public void view() {
		Role model = Role.dao.findById(getPara());
		setAttr("model", model);
		render(path + "view.html");
	}

	/**
	 * 删除数据
	 */
	public void delete() {
		Role.dao.deleteById(getPara());
		list();
	}

	public void edit() {
		Role model = Role.dao.findById(getPara());
		setAttr("selectRole", RoleService.service.selectRole(model.getStr("parentids")));
		setAttr("model", model);
		render(path + "edit.html");
	}

	public void save() {
		String ids = getPara();
		Role model = getModel(Role.class);
		RoleService.service.saveOrUpdate(ids, model);

		renderMessage("保存成功");
	}

	/**
	 * 跳转到授权页面
	 * 
	 */
	public void auth() {
		String roleid = getPara();
		// 获取根目录（一级目录）
		List<Module> rootList = MenuService.service.getParentMoudles();

		// 获取子目录(二级目录)
		Map<String, List<Operator>> secondList = new HashMap<String, List<Operator>>();
		for (Module module : rootList) {
			secondList.put(module.getStr("ids"), MenuService.service.getOperatorByModuleids(module.getStr("ids")));
		}

		String operatorids = RoleService.service.getOperatoridsByRoleid(roleid);
		setAttr("rootList", rootList);
		setAttr("map", secondList);

		setAttr("roleid", roleid);
		setAttr("menus", operatorids);
		render(path + "auth.html");
	}

	/**
	 * 保存授权信息
	 */
	public void auth_save() {
		String roleid = getPara("roleid");
		String menus = getPara("menus");
		RoleService.service.saveAuth(roleid, menus, getSessionUser().getUseriD());
		renderMessage("保存成功");
	}

}
